<template>
  <div class="allocate-detail-page">
    <!-- 调拨单基本信息 -->
    <el-descriptions title="调拨物品详情" class="desc-card" :column="3" border>
      <el-descriptions-item label="调出仓库">{{ order.outName }}</el-descriptions-item>
      <el-descriptions-item label="调入仓库">{{ order.inName }}</el-descriptions-item>
      <el-descriptions-item label="调拨日期">{{ order.transferDate }}</el-descriptions-item>
    </el-descriptions>

    <!-- 调拨物品列表 -->
    <el-table :data="tableData" class="goods-table" border style="margin-top: 20px;">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="code" label="物品编码" width="140" />
      <el-table-column prop="name" label="物品名称" min-width="160" />
      <el-table-column prop="availableStock" label="可用库存" width="100" />
      <el-table-column prop="pending_transfer_total" label="待审核调拨总数" width="140">
        <template #default="{ row }">
          <span style="color: red; font-weight: bold;">{{ row.pending_transfer_total }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="applyNum" label="申请数量" width="100" />
      <el-table-column prop="auditNum" label="审批数量" width="120">
        <template #default="{ row }">
          <el-input-number v-model="row.auditNum" :min="0" :max="row.applyNum" size="small" />
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="计量单位" width="100" />
      <el-table-column prop="price" label="单价" width="80" />
      <el-table-column label="审批金额" width="120">
        <template #default="{ row }">
          <span style="color: red; font-weight: bold;">{{ (row.auditNum * row.price).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <img v-if="row.picurl" :src="row.picurl" style="max-width: 100px; max-height: 80px; object-fit: cover;" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80">
        <template #default="{ $index }">
          <el-button type="text" @click="deleteRow($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 审核意见 -->
    <div class="audit-section">
      <div class="total-amount">审批总金额：<span>{{ totalAmount }}</span> 元</div>
      <el-form-item label="审核意见：">
        <el-input v-model="auditNote" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="500字以内" />
      </el-form-item>
      <div class="btn-group">
        <el-button type="primary" @click="passAuditHandler">审核通过</el-button>
        <el-button type="danger" @click="failAuditHandler">审核不通过</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { queryAudit, passAudit } from "@/api/allocate/allocate.js";

const route = useRoute();
const order = ref({
  id: route.query.id || "",
  inName: route.query.inName || "",
  outName: route.query.outName || "",
  transferDate: route.query.transferDate || "",
});

const tableData = ref([]);
const auditNote = ref("");

// 初始化查询
async function init() {
  let params = {
    id: 0,
    orderId: order.value.id,
    page: 1,
    pageSize: 10,
  };
  const res = await queryAudit(params);
  if (res.code === 200) {
    tableData.value = res.data.list.map(item => ({
      ...item,
      auditNum: item.auditNum || 0, // 默认审批数量
      pending_transfer_total: item.pendingTransferTotal // 手动映射
    }));
  } else {
    ElMessage.error("加载调拨明细失败");
  }
}
onMounted(() => {
  init();
});

// 审批总金额动态计算
const totalAmount = computed(() =>
  tableData.value.reduce((sum, row) => sum + row.auditNum * row.price, 0).toFixed(2)
);

// 删除行
function deleteRow(index) {
  ElMessageBox.confirm("确定删除此物品吗？", "提示", { type: "warning" })
    .then(() => {
      tableData.value.splice(index, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {});
}

// 审核通过
async function passAuditHandler() {
  const payload = {
    auditStatus: 2,
    itemAuditDTOS: tableData.value.map(item => ({
      applyNum: item.applyNum,
      auditNum: item.auditNum,
      availableStock: item.availableStock,
      id: item.id,
      pending_transfer_total: item.pending_transfer_total,
    })),
    note: auditNote.value,
    orderId: order.value.id,
  };
  const res = await passAudit(payload);
  if (res.code === 200) {
    ElMessage.success("审核通过成功");
    init(); // 重新加载数据
  } else {
    ElMessage.error("审核失败");
  }
}

// 审核不通过（接口可后续实现）
function failAuditHandler() {
  ElMessage.warning("审核不通过接口待实现");
}
</script>

<style scoped>
.allocate-detail-page {
  padding: 20px;
  background-color: #f9fafc;
}

.desc-card {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 24px;
}

.goods-table {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.audit-section {
  margin-top: 20px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.total-amount {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}
.total-amount span {
  color: red;
}

.btn-group {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>
